const express = require('express')
const fs = require('fs')
const router = express.Router()
const formidable = require('formidable');
const resSend = require('../utils/resSend')

// 文件上传
router.post('/file', async(req, res) => {
    let path = req.user.email
    var form = new formidable.IncomingForm(); // 创建上传表单
    form.encoding = 'utf-8'; // 设置编辑
    form.uploadDir = './static/'; // 设置上传目录
    form.keepExtensions = true; // 保留后缀
    form.maxFieldsSize = 20 * 1024 * 1024; // 文件大小
    form.parse(req, function(err, fields, files) {
        if (err) {
            resSend(res,500,err)
        };
        try {
            // 若文件流的键名为uplaodFile，则filename = files.uplaodFile.name
            var filename = files.file[0].originalFilename;
            // 对文件名进行处理，以应对上传同名文件的情况
            var nameArray = filename.split('.');
            var type = nameArray[nameArray.length - 1];
            var name = '';
            for (var i = 0; i < nameArray.length - 1; i++) {
                name = name + nameArray[i];
            }
            var rand = Math.random() * 100 + 900;
            var num = parseInt(rand, 10);
            // var num = Date.now()
            var avatarName = path.slice(0,5)+'_'+name + String(num) + '.' + type;
            // var avatarName = num + filename
            var newPath = form.uploadDir + avatarName;
            // 若文件流的键名为uplaodFile，则fs.renameSync(files.uplaodFile.path, newPath)
            fs.renameSync(files.file[0].filepath, newPath); //重命名
            resSend(res,200,'文件上传成功',{url: avatarName})
        } catch (err) {
            console.log(err);
            resSend(res,500,"上传失败！")
            return;
        }
    });
});

module.exports = router